package ink.tsg.manydatasource.controller;

import com.alibaba.druid.DbType;
import com.alibaba.druid.pool.DruidDataSource;
import ink.tsg.manydatasource.entity.User;
import ink.tsg.manydatasource.mapper.UserMapper;
import ink.tsg.manydatasource.service.UserService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * @author tsg
 * @version 1.0
 * @description: 参考:https://zhuanlan.zhihu.com/p/373472020
 * @date 2022/5/4 16:47
 */
@RequestMapping
@RestController
public class AddMyDataSourceController implements BeanFactoryAware, ApplicationContextAware {

    private DefaultListableBeanFactory beanFactory;

    @Autowired
    private UserMapper userMapper;

    @PostMapping("addMyDataSource")
    public String addMyDataSource(@RequestBody Map<String,String> map){
//        BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DruidDataSource.class);
//        DruidDataSource druidDataSource = new DruidDataSource();
//        druidDataSource.setUrl("jdbc:mysql://localhost:3306/demo?characterEncoding=utf8");
//        druidDataSource.setPassword("root");
//        druidDataSource.setUsername("Hlxd@123456");
//        druidDataSource.setDbType(DbType.mysql);
//        druidDataSource.setMaxActive(20);
//        druidDataSource.setMinIdle(10);
//        druidDataSource.setInitialSize(5);
//        druidDataSource.setValidationQuery("SELECT 1 FROM DUAL");
//        druidDataSource.setTestWhileIdle(true);
//        beanFactory.registerSingleton("db3", druidDataSource);
//        // 重新执行依赖注入
//        beanFactory.autowireBean(beanFactory.getBean(DataSource.class));
        List<User> users = userMapper.selectList(null);
        System.out.println(users);
        return "success";
    }

    @GetMapping("/getDataSources")
    public String getDataSources() {
        Map<String, DataSource> dataSourceMap = beanFactory.getBeansOfType(DataSource.class);
        dataSourceMap.forEach((s, dataSource) -> {
            System.out.println(s + " ======== " + dataSource);
        });
        return "success";
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }
}
